package net.cyue.web.easyquery.provider.http.spring;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletRegistration;
import net.cyue.web.easyquery.core.http.adapter.AbstractHTTPServer;
import net.cyue.web.easyquery.core.util.TaskUtil;
import net.cyue.web.easyquery.provider.http.servlet.HTTPServletProviderTaskType;
import net.cyue.web.easyquery.provider.http.spring.util.SpringContextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;


public class SpringHTTPServer extends AbstractHTTPServer<ServletContext> {

    private static final String DISPATCHER_SERVLET_NAME = "dispatcherServlet";

    private final Logger logger = LoggerFactory.getLogger(this.toString());
    private boolean isInit = false;
    private ServletContext context;

    public SpringHTTPServer() {
        this(null);
    }
    public SpringHTTPServer(ServletContext context) {
        this.context = context;
        TaskUtil.addTask(HTTPServletProviderTaskType.INIT, (servletContext) -> {
            this.context = servletContext;
            if (!SpringContextUtil.hasApplicationContext()) {
                this.initSpringApplication();
            } else {
                this.isInit = true;
            }
        });
    }

    @Override
    public ServletContext getPrototype() {
        return this.context;
    }

    private void initSpringApplication() {
        if (this.isInit) {
            return;
        }
        this.isInit = true;
        this.logger.info("创建默认 WebApplicationContext...");
        // 创建 WebApplicationContext
        AnnotationConfigWebApplicationContext webApplicationContext = SpringContextUtil.createConfigWebApplicationContext();
        // 初始化 context
        webApplicationContext.setServletContext(this.context);
        // 将 SpringHTTPServer 注册到 BeanFactory
        webApplicationContext.addApplicationListener((ApplicationListener<ContextRefreshedEvent>) event -> {
            this.logger.info("Spring 上下文刷新完成，执行初始化任务...");
            DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) webApplicationContext.getBeanFactory();
            beanFactory.registerSingleton(this.getClass().getSimpleName(), this);
        });
        // 初始化 SpringMVC
        ServletRegistration.Dynamic dynamic = this.context.addServlet(
            DISPATCHER_SERVLET_NAME,
            new DispatcherServlet(webApplicationContext)
        );
        dynamic.addMapping("/*");
        // dynamic.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
        // dynamic.setInitParameter("contextConfigLocation", DefaultSpringConfig.class.getName());
        dynamic.setLoadOnStartup(1);
    }
}
